package two_shang.otherTest.ThreadPackage;

public class 管程法 {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();

        new Productor(synContainer).start();
        new Consumer(synContainer).start();
    }
}

//生产者
class Productor extends Thread {
    SynContainer container;

    public Productor(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了第" + i + "只鸡");
        }
    }
}

//消费者
class Consumer extends Thread {
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了第-->" + container.pop().foodId + "只鸡");
        }
    }
}

//产品
class Chicken {
    int foodId;

    public Chicken(int foodId) {
        this.foodId = foodId;
    }

}

//缓冲区
class SynContainer {
    //    容器大小
    Chicken[] chickens = new Chicken[10];
    //容器计数器
    int count = 0;

    //    生产
    public synchronized void push(Chicken chicken) {
        if (this.count == chickens.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("货舱已满");
        }
        //生产满了，通知消费
        chickens[count++] = chicken;
        this.notifyAll();

    }

    //    消费
    public synchronized Chicken pop() {
        if (this.count == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("暂时没货");
        }

        Chicken chicken = chickens[--count];
        //吃完了，通知生产
        this.notifyAll();
        return chicken;
    }

}

